<?php

namespace app\model\v1\recovery;

use crmeb\traits\ModelTrait;
use think\Model;


class RecoveryProductCategory extends Model
{
    use ModelTrait;


    protected $updateTime = false;
    protected $createTime = false;


    const FREE_MARK_CATE_NAME = '自由市场';
    const FREE_IDLE_CATE_NAME = '办公闲置';
    const CARD_IDLE_CATE_NAME = '卡类转让';

    public function searchPidAttr($query, $value)
    {
        $query->where('pid', $value);
    }

    public function searchCateNameAttr($query, $value)
    {
        $query->where('cate_name', 'like', '%' . $value . '%');
    }


    /**
     * 获取自由市场的分类id
     * @return float|mixed|string
     */
    public static function getFreeMarkCateId()
    {
        $cate_id = self::where("cate_name", self::FREE_MARK_CATE_NAME)->where(["pid"=>0,"status"=>1])->value("id");
        return $cate_id;
    }


    /**
     * 获取卡类转让的分类id
     * @return float|mixed|string
     */
    public static function getCardCateId()
    {
        $cate_id = self::where("cate_name", self::CARD_IDLE_CATE_NAME)->where(["pid"=>0,"status"=>1])->value("id");
        return $cate_id;
    }


    public static function getFreeIdleCateId()
    {
        $cate_id = self::where("cate_name", self::FREE_IDLE_CATE_NAME)->where(["pid"=>0,"status"=>1])->value("id");
        return $cate_id;
    }


    public static function getCategoryIdByName($name = '', $pid=0)
    {
        $cate_id = self::where("cate_name", $name)->where(["pid"=>$pid])->value("id");
        return $cate_id;
    }


    /**
     * 分类管理列表
     * @param $param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getRecoveryCateList($param = [])
    {
        $order = ["id"=>"desc"];

        $data["data"] = self::whereNull("delete_time")
            ->field("*, 
            case when status=1 then '启用' 
            when status=2 then '禁用' 
            end as status_text ")
            ->where(function ($query) use ($param){
                if(!empty($param['time'])){    //根据创建日期搜索
                    $wheretime = explode (',',$param['time']);
                    $query->where('create_time', 'between', [strtotime($wheretime[0]),strtotime($wheretime[1])]);
                }
                if(!empty($param["word"])) $query->where("cate_name",'like', '%'.$param["word"].'%');
                if(!empty($param["cate_id"])) $query->where("type", $param["cate_id"]);
            })
            ->order($order)
            ->page($param['page'], $param['limit'])
            ->select()
            ->each(function (&$item) {
                $item['create_time'] = $item['create_time'] ? date("Y-m-d H:i:s", $item['create_time']) : $item['create_time'];
            })
            ->toArray();

        $data["count"] = self::whereNull("delete_time")
            ->field("*")
            ->where(function ($query) use ($param){
                if(!empty($param['time'])){    //根据创建日期搜索
                    $wheretime = explode (',',$param['time']);
                    $query->where('create_time', 'between', [strtotime($wheretime[0]),strtotime($wheretime[1])]);
                }
                if(!empty($param["word"])) $query->where("cate_name",'like', '%'.$param["word"].'%');
                if(!empty($param["cate_id"])) $query->where("type", $param["cate_id"]);
            })
            ->count();

        return $data;
    }



    /**
     * 分类管理列表 - 添加
     * @param $param
     * @return int|string
     */
    public static function addRecoveryCate($param = [])
    {
        $add = [
            "pid"           => $param["pid"],  //父id
            "cate_name"     => $param["cate_name"] ?? '', //分类名称
            "sort"          => $param["sort"] ?? '',  //排序
            "pic"           => $param["pic"] ?? '',  //图标
            "create_time"   => time(),
        ];
        return self::insert($add);
    }


    /**
     * 分类管理列表 - 编辑
     * @param $param
     * @return RecoveryProductCategory
     */
    public static function updateRecoveryCate($param = [])
    {
        $update["update_time"] = time();  //更新时间
        if(!empty($param["cate_name"]))     $update["cate_name"] = $param["cate_name"];  //分类名称
        if(!empty($param["sort"]))          $update["sort"] = $param["sort"]; //排序
        if(!empty($param["pid"]))           $update["pid"] = $param["pid"]; //父id
        if(!empty($param["pic"]))           $update["pic"] = $param["pic"]; //图标

        return self::where("id", $param["id"])->update($update);
    }




    public static function enableRecoveryCate($param = [])
    {
        //获取用户发送的id，根据状态修改当前banner的启用禁用状态
        $status = self::where("id", $param['id'])->value("status");
        $msg = '';
        if($status == 1){   //1启用 2禁用
            $enable = 2;
            $msg = "禁用成功";
        }else{
            $enable = 1;
            $msg = "启用成功";
        }
        self::where("id", $param['id'])->update(['status' => $enable]);
        return $msg;
    }


    public static function getCategoryPidList($param = [])
    {
        return self::whereNull("delete_time")->where(["pid" => 0, "is_show" => 1])->select()->toArray();
    }



    public static function getProCategoryList($param = [])
    {
        $data = RecoveryProductCategory::field('id,cate_name,pid as parent_id,sort,pic')->select();
        return self::buildTree($data);
    }


    public static function buildTree($data, $parentId = 0) {
        $tree = array();
        foreach ($data as $item) {
            if ($item['parent_id'] == $parentId) {
                $children = self::buildTree($data, $item['id']);
                if (!empty($children)) {
                    $item['children'] = $children;
                }
                $tree[] = $item;
            }
        }
        return $tree;
    }



    public static function getChildrenIds(int $id)
    {
        $data = [];
        if(empty($id)) return $data;

        $child1 = self::where("pid", $id)->column("id") ?? [];
        if(!empty($child1)){
            array_push($data, $id);
            $data = array_merge($data, $child1);
            $child2 = self::whereIn("pid", $child1)->column("id") ?? [];
            if(!empty($child2)){
                $data = array_merge($data, $child2);
                $child3 = self::whereIn("pid", $child2)->column("id") ?? [];
                if(!empty($child3)){
                    $data = array_merge($data, $child3);
                }
            }
        }else{
            $data = [$id];
        }
        return $data;
    }


    public static function getCatePidName($cate_id)
    {
        $arr = [];
        $parent = self::where("id", $cate_id)->find();
        if(!empty($parent)){
            $arr[] = $parent['cate_name'] ?? '';
            if($parent["pid"] > 0){
                $parent2 = self::where("id", $parent["pid"])->find();
                if(!empty($parent2)){
                    $arr[] = $parent2['cate_name'] ?? '';
                    $parent3 = self::where("id", $parent2["pid"])->find();
                    if(!empty($parent3)){
                        $arr[] = $parent3['cate_name'] ?? '';
                    }
                }
            }
        }
        return !empty($arr) ? implode("/", array_reverse($arr)) : '';
    }



}